package config

import (
	"github.com/spf13/viper"
	"log"
	"sync"
)

var ObsOnce sync.Once
var MongoOnce sync.Once
var OfficeOnce sync.Once

// 本地环境
var configEnv = "config"

// 线上环境
//var configEnv = "config"

type ObsConfig struct {
	Host   string
	SM4Key string
	SM4Iv  string
}

type MongoConfig struct {
	Host     string
	Port     int64
	User     string
	Password string
	Db       string
}

type OfficeConfig struct {
	Host string
}

var obsConfig *ObsConfig
var mongoConfig *MongoConfig
var officeConfig *OfficeConfig

func LoadObsConfig() (*ObsConfig, error) {
	if obsConfig == nil {
		ObsOnce.Do(func() {
			viper.SetConfigName(configEnv)
			viper.SetConfigType("toml")
			viper.AddConfigPath(".")
			err := viper.ReadInConfig()
			if err != nil {
				log.Fatalf("read config failed: %v", err)
			}
			obsConfig = &ObsConfig{
				Host:   viper.Get("obs.Host").(string),
				SM4Key: viper.Get("obs.SM4Key").(string),
				SM4Iv:  viper.Get("obs.SM4Iv").(string),
			}
		})
	}
	return obsConfig, nil
}

func LoadMongoConfig() (*MongoConfig, error) {
	if mongoConfig == nil {
		MongoOnce.Do(func() {
			viper.SetConfigName(configEnv)
			viper.SetConfigType("toml")
			viper.AddConfigPath(".")
			err := viper.ReadInConfig()
			if err != nil {
				log.Fatalf("read config failed: %v", err)
			}
			mongoConfig = &MongoConfig{
				Host:     viper.Get("mongo.Host").(string),
				Port:     viper.Get("mongo.Port").(int64),
				User:     viper.Get("mongo.User").(string),
				Password: viper.Get("mongo.Password").(string),
				Db:       viper.Get("mongo.Db").(string),
			}
		})
	}
	return mongoConfig, nil
}

func LoadOfficeConfig() (*OfficeConfig, error) {
	if officeConfig == nil {
		OfficeOnce.Do(func() {
			viper.SetConfigName(configEnv)
			viper.SetConfigType("toml")
			viper.AddConfigPath(".")
			err := viper.ReadInConfig()
			if err != nil {
				log.Fatalf("read config failed: %v", err)
			}

			officeConfig = &OfficeConfig{
				Host: viper.Get("office.Host").(string),
			}
		})
	}
	return officeConfig, nil
}
